'use strict'

const Service = require('egg').Service;

class UserService extends Service {

    async register(userinfo) {
        const { ctx, app } = this;
        const { userid, username, password, phone, roll, group } = userinfo;
        
        let user = await ctx.model.Users.find({ userid });
        if (user && user.length > 0) return;

        user = await ctx.model.Users.find({ username });
        if (user && user.length > 0) return;

        const currentDate = new Date().getTime();
        userinfo.createTs = currentDate;
        userinfo.changeTs = currentDate;
        await ctx.model.Users.create(userinfo, err => {
            if (err) console.log(err);
        })
    
        const token = app.jwt.sign({
            username,
            password,
            date: currentDate,
        }, app.config.jwt.secret,
        {
            expiresIn: '3600s',
        });
        return {
            userid,
            username,
            group,
            roll,
            token,
        };
    }

    async login(username, password) {
        const { ctx, app } = this;
        const userArr = await ctx.model.Users.find({ username, password });
        if (!userArr || userArr.length != 1) return;
        
        const { userid, group, roll } = userArr[0];

        const token = app.jwt.sign({
            username,
            password,
            date: new Date().getTime()
        }, app.config.jwt.secret,
        {
            expiresIn: '3600s',
        });
        return {
            userid,
            username,
            group,
            roll,
            token,
        };
    }

    async getUser(userid) {
        const { ctx, app } = this;
        const userArr = await ctx.model.Users.find({ userid });
        if (!userArr || userArr.length != 1) return;
        
        const user = userArr[0];
        return user;
    }

    async updateUser(userid, userInfo) {
        const { ctx, app } = this;
        console.log(userid);
        console.log(userInfo);
        await ctx.model.Users.updateOne({ userid }, userInfo, err => {
            if (err) return false;
            return true;
        });
    }
}

module.exports = UserService;